import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

// 创建一个加载失败时显示的组件
const createErrorComponent = (moduleName) => {
  return {
    name: `${moduleName}Error`,
    template: `
      <div style="padding: 40px; text-align: center;">
        <h3 style="color: #ff4d4f; margin-bottom: 16px;">模块加载失败</h3>
        <p style="color: #666; margin-bottom: 24px;">无法加载 ${moduleName} 模块，请确保该模块服务已启动</p>
        <div style="background-color: #f5f5f5; padding: 16px; border-radius: 4px; text-align: left; max-width: 500px; margin: 0 auto;">
          <p style="margin: 8px 0;"><strong>可能的原因：</strong></p>
          <ul style="list-style-type: disc; padding-left: 20px; margin: 8px 0;">
            <li>远程服务未启动</li>
            <li>网络连接问题</li>
            <li>模块配置错误</li>
          </ul>
          <p style="margin: 8px 0;"><strong>解决方案：</strong></p>
          <p style="margin: 8px 0;">请确保运行了 <code>npm run serve:all</code> 命令启动所有服务</p>
          <button style="margin-top: 16px; padding: 8px 16px; background-color: #1890ff; color: white; border: none; border-radius: 4px; cursor: pointer;" @click="window.location.reload()">
            刷新页面重试
          </button>
        </div>
      </div>
    `
  }
}

// 直接使用动态导入来加载远程组件
const UserList = () => import('userApp/UserList').catch(error => {
  console.error('Failed to load UserList component from userApp:', error);
  return createErrorComponent('用户管理');
});

const OrderList = () => import('orderApp/OrderList').catch(error => {
  console.error('Failed to load OrderList component from orderApp:', error);
  return createErrorComponent('订单管理');
});

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/users',
    name: 'users',
    component: UserList,
    meta: {
      title: '用户管理'
    }
  },
  {
    path: '/orders',
    name: 'orders',
    component: OrderList,
    meta: {
      title: '订单管理'
    }
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 添加路由导航守卫，用于设置页面标题
router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = to.meta.title + ' - 企业管理系统';
  } else {
    document.title = '企业管理系统';
  }
  next();
})

export default router
